'use strict';

module.exports = (option, app) => {
  return async function (ctx, next) {
    try {
      // console.log("这是中间层1",ctx)
      await next();
    } catch (err) {
      
    
    switch (err.message) {
        case 'invalid token':
          ctx.body = {
            success: false,
            status: 4000,
            // test: "invalid token",
            code: 401,
            msg:'invalid token'
          };
          // app.loggers.info(`  status OK`);//会打印到egg.web.log文件中
          // console.log(app.loggers)
          // app.emit('error', "这是日志打印测试", this);//此可以用于调试打印到日志: log/example-web.log
          ctx.status = 401;
          break;
          case 'jwt expired':          
          ctx.body  = {
            success: false,
            status: 0,
            msg: '登录已过期,请重新登录'
          } ;          
          ctx.status = 401;
          break; 
          case 'invalid signature': //无效的签名         
          ctx.body  = {
            success: false,
            status: 4000,
            msg: '非法的请求',
          }           
          ctx.status = 401;
          break;
          case 'SequelizeDatabaseError':
          ctx.body = {
            success:false,
            status:2222,
            msg:'服务器错误,请稍候再试'
          } ;
          ctx.status = 500;
          break;           
          case 'isSigined':
          ctx.body =  {
            success:false,
            status:2000,
            msg:'AI的IP已是最新', 
          }
          break; 
          case 'temp_VIP_forbidden_sign':
          ctx.body =  {
            success:false,
            status:2001,
            msg:'您是临时VIP客户,请联系客服进行购买', 
          }
          break;       
          case 'logout':
          app.emit('error', JSON.stringify(err), 122);
            
          break
        default:
          // console.log(err)
          console.log("这是中间层的报错处理",err)
          // app.loggers.info(`中间件未知错误: `+JSON.stringify(err));// 在egg.web.log中查看
          app.emit('error', "这是日志打印测试11", JSON.stringify(err));
          ctx.body =  {
            success:false,
            status:2000,
            msg:app.config.env=="local"?err:'未知错误,请联系客服',//调试用返回真实,
          }

      }

    }
  };
};